package com.heo.music.player.controller;

import com.heo.music.player.config.UploadConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * created on 2024-05-11 10:39
 *
 * @author 星天无极
 **/
@Api(tags = "上传文件接口接口")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1")
public class UploadController {

    private final UploadConfig uploadConfig;

    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public String upload(@RequestPart MultipartFile file) throws IOException {
        if (file == null) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "文件为空");
        }
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "文件名错误");
        }
        int index = originalFilename.lastIndexOf(".");
        String suffixName = originalFilename.substring(index);

        String tmpFilename = UUID.randomUUID() + suffixName;

        Path tempFile = Paths.get(uploadConfig.getPath(), tmpFilename);
        file.transferTo(tempFile);
        return tmpFilename;
    }
}
